package cn.orange.ch10_dynamicprogramming;

/**
 * LC213.打家劫舍II
 */
public class LC213 {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int n = nums.length;
        if (n == 1) return nums[0];
        if (n == 2) return Math.max(nums[0], nums[1]);
        return Math.max(robAction(nums, 0, n - 2), robAction(nums, 1, n - 1));
    }

    private int robAction(int[] nums, int start, int end) {
        int n = end - start + 1;
        int[] dp = new int[n];
        dp[0] = nums[start];
        dp[1] = Math.max(nums[start], nums[start + 1]);
        for (int i = start + 2; i <= end; i++) {
            dp[i - start] = Math.max(dp[i - start - 1], nums[i] + dp[i - start - 2]);
        }
        return dp[n - 1];
    }

    public static void main(String[] args) {
        LC213 alg = new LC213();
        System.out.println(alg.rob(new int[]{1, 2, 3, 1}));
        System.out.println(alg.rob(new int[]{2, 3, 2}));
    }
}
